package where2go.sctu.com.zhiyou.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import where2go.sctu.com.zhiyou.MyApplication;
import where2go.sctu.com.zhiyou.R;
import where2go.sctu.com.zhiyou.entity.Modify;
import where2go.sctu.com.zhiyou.entity.NewUser;
import where2go.sctu.com.zhiyou.utils.HeaderStringRequest;
import where2go.sctu.com.zhiyou.utils.ShareUtils;

/**
 * Created by lenovo on 2018/5/28.
 */

public class ModifyInformationActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView imageView;
    private EditText userName;
    private EditText nickName;
    private EditText userDetail;
    private ImageView image;
    private EditText sex;
    private EditText birthday;
    private Button btnSave;
    private NewUser.DataBean user = new NewUser.DataBean();
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    private NewUser users = new NewUser();
    private Modify modify = new Modify();
    private String url1 = "http://47.104.80.155/youyiyou/resources/img/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.modify_imformation);
        initView();
        getUserInformation();
        imageView = (ImageView) findViewById(R.id.modify);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initView() {
        userName = (EditText) findViewById(R.id.username_modify);
        nickName = (EditText) findViewById(R.id.nickname_modify);
        userDetail = (EditText) findViewById(R.id.user_detail_modify);
        sex = (EditText) findViewById(R.id.gender_modify);
        birthday = (EditText) findViewById((R.id.birthday_modify));
        image = (ImageView) findViewById(R.id.image_modify);
        btnSave = (Button) findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this);
    }

    private void getUserInformation() {
        final String url = "http://47.104.80.155/youyiyou/users/details/show";
        HeaderStringRequest request = new HeaderStringRequest(com.android.volley.Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                Type type = new TypeToken<NewUser>() {
                }.getType();
                users = gson.fromJson(response, type);
                user = users.getData();
                userName.setText(user.getUserName());
                nickName.setText(user.getUserNickName());
                userDetail.setText(user.getUserDetail());
                if (user.getUserSex() == 1) {
                    sex.setText("女");
                } else {
                    sex.setText("男");
                }

                if (user.getUserBirthday() != null) {
                    String s = format.format(new Date(Long.parseLong(user.getUserBirthday())));
                    birthday.setText(s);
                } else
                    birthday.setText("");

                ImageRequest imageRequest = new ImageRequest(url1 + user.getUserAvatarAddress(),
                        new Response.Listener<Bitmap>() {
                            @Override
                            public void onResponse(Bitmap bitmap) {
                                image.setImageBitmap(bitmap);
                            }
                        }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //请求失败 设置默认图片
                        image.setImageResource(R.mipmap.ic_launcher);
                    }

                });
                MyApplication.getHttpQueues().add(imageRequest);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("authorization", ShareUtils.getString(ModifyInformationActivity.this, "token", null));
                return map;
            }
        };
        request.setTag("modify");
        MyApplication.getHttpQueues().add(request);
    }

    private void postUserInformation() {
        final String url = "http://47.104.80.155/youyiyou/users/details/revise";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("userDetail", userDetail.getText().toString());
        map.put("userNickName", nickName.getText().toString());
        map.put("userName", userName.getText().toString());
        if (sex.getText().equals("男")) {
            map.put("userSex", "1");
        } else if (sex.getText().equals("女")) {
            map.put("userSex", "0");
        }
        try {
            Date date = format.parse(birthday.getText().toString());
            map.put("userBirthday", date.toString());
        } catch (ParseException e) {
            e.printStackTrace();
            Log.e("ParseException", e.toString());
        }
        //final JsonObject object = new JsonObject();  //将map转化成json格式的数据

        Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        final String jsonStr=gson.toJson(map);

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client=new OkHttpClient();//创建OkHttpClient对象
                MediaType JSON=MediaType.parse("application/json; charset=utf-8");
                RequestBody body=RequestBody.create(JSON, jsonStr);
                Request request=new Request.Builder()
                        .addHeader("Authorization",
                                ShareUtils.getString(ModifyInformationActivity.this,
                                        "token",
                                        null))
                        .addHeader("Content-Type","application/json")
                        .url("http://47.104.80.155/youyiyou/users/details/revise")
                        .post(body)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(ModifyInformationActivity.this,
                                e.toString(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, okhttp3.Response response) throws IOException {
                        Log.d("RESEPONSE",response.toString());
                    }
                });
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                MyApplication.getHttpQueues().cancelAll("modify");
                //postUserInformation();
                //Toast.makeText(ModifyInformationActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                break;
        }
    }

}
